import VueRouter from "vue-router";
import Login from "@/pages/Login.vue";
import Main from '@/pages/Main.vue';
import User from "@/pages/User.vue";
import Home from "@/pages/Home.vue";
import Mall from "@/pages/Mall.vue";
import PageOne from "@/pages/PageOne.vue";
import PageTwo from "@/pages/PageTwo.vue";
import Cookie from "js-cookie";

const router= new VueRouter({
    // 浏览器模式设置，设置为history模式
    // mode:'history',
    routes:[
        {
            name:'login',
            path:"/login",
            component:Login,
            meta:{title:"登录"},
        },
        {
            // 子路由
            name:"main",
            path:'/',
            redirect:"/home",  //重定向 当路径为/，则重定向home
            component:Main,
            children:[
                    /*{
                        name:"user",
                        path:"user",
                        component:User,
                        meta:{title:"用户管理"}
                    },
                    {
                        name:"home",
                        path:"home",
                        component:Home,
                        meta:{title:"首页"}
                    },
                    {
                        name:"mall",
                        path:"mall",
                        component:Mall,
                        meta:{title:"商品管理"}
                    },
                    {
                        name:"page1",
                        path:"page1",
                        component:PageOne,
                        meta:{title:"页面1"}
                    },
                    {
                        name:"page2",
                        path:"page2",
                        component:PageTwo,
                        meta:{title:"页面2"}
                    }*/
            ]
        }

    ]
})
//添加全局前置导航守卫
router.beforeEach((to,from,next)=>{
    //判断token存不存在
    const token=Cookie.get('token')
    //token不存在，说明当前用户是未登录，应该跳转至登录页
    if(!token&&to.name!=='login'){
        next({name:'login'})
    }else if(token && to.name=="login"){   //token存在，说明用户登录，此时跳转至首页
        next({name:'home'})
    }else{
        next()
    }
})
// 后置路由守卫
router.afterEach((to,from)=>{
    document.title=to.meta.title||"通用后台管理系统"
})
export default router
